<style lang='less' >
  #poblishPage{
    padding: 30px 0;
    .textarea{
      position:relative;
      width:620px;
      height:120px;

    }
    .el-textarea__inner{
      position:relative;
      height:120px;
    }
    .el-button--success{
      position: absolute;
      right: 0;
      top: 0;
      height: 100%;
      width: 50px;
    }
    .el-form{
      padding: 0;
      .el-button{
        margin: 0;
        width: auto;
      }
    }
    .resultBox{
      border: 1px solid rgb(191, 212, 217);
      border-radius: 4px;
      height: 120px;
      line-height: 20px;
      overflow:auto;
      .errTels{
        color: red;
      }
    }
    .btnBox{
      margin:30px 0 0 120px;
      .el-button{
        width:150px;
        margin-right:40px;
        &:first-child{
          border-color:#63c5ce;
          color:#63c5ce;
        }
      }
    }
  }
</style>

<template>
  <div id='poblishPage'>
    <el-form :model="formData" :rules="rules" ref="formData" label-width="120px" class="demo-ruleForm" v-if='couponDetail'>
      <el-form-item label="卡券：" >
        <span> {{couponDetail.name}} </span>
      </el-form-item>

      <el-form-item label="卡券类型：" >
        <span>{{cardType}}</span>
      </el-form-item>

      <el-form-item label="每人发放数量：" prop='cardNum'>
        <el-input-number v-model.number="formData.cardNum" type="number" :min="1"  :max='remainderNum'></el-input-number>
      </el-form-item>

      <el-form-item label="派发用户：" prop='userType'>
        <el-select v-model="formData.userType" placeholder="请选择">
          <el-option v-for="item in userTypeArr" :key="item.value" :label="item.name" :value="item.value"></el-option>
          </el-option>
        </el-select>
      </el-form-item>

      <div v-if='formData.userType==3'>
        <el-form-item label="导入名单：" >
          <el-input style="width:250px;margin-right:30px;" v-model="path" :disabled="true"></el-input>
          <el-upload
            style='display: inline-block;'
            ref='upload'
            class="upload-demo"
            :show-file-list='false'
            :multiple='false'
            :auto-upload="false"
            :action='""'
            name='filename'
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :on-change='handleChange'>
            <el-button type="warning">浏览</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="用户帐号：" prop='userList' class='textarea'>
          <el-input v-model.lazy="formData.userList" type="textarea"></el-input>
            <el-button type="success" @click="verifyTels" :loading='isAjax==1'><br/>校<br/>验<br/>手<br/>机<br/>号<br/>码</el-button>
        </el-form-item>

        <el-form-item label="校验结果：" class='textarea'>
          <div class="resultBox" >
            <div class="errTels" v-if='result && result.invalidatedUsers && result.invalidatedUsers.length >0'>
              错误信息：<br/>
              <div v-for='item in result.invalidatedUsers'>
                {{item.userMobile}}
              </div>
            </div>
            <div v-if='result && result.validatedUsers && result.validatedUsers.length >0'>
              正确信息：<br/>
              <div v-for='item in result.validatedUsers'>
                {{item.userName}} {{item.userMobile}}
              </div>
            </div>
          </div>
        </el-form-item>

      </div>
    </el-form>

    <div class='btnBox'>
      <el-button @click='goPage("couponList")'>返回</el-button>
      <el-button type="primary" @click='sendCoupon' :loading='isAjax==2'>确认派送</el-button>
    </div>

  </div>
</template>

<script>
  import {getCouponDetail, postCheckUserValidate, postSendCoupon } from 'api/coupon/index.js'
  import {typeOption, userTypeArr, formRules} from '../config.js'
  import XLSX from 'xlsx'
  import {regTel} from 'config/verify.js'


  export default {
    props:[''],
    components:{
    },
   
    data(){
      return{
        uuid:this.$route.query.uuid,
        userTypeArr:userTypeArr,
        isPublishSucced:false,
        rules:formRules,
        couponDetail:null,
        path:'',//上传excel显示的文件名
        isAjax:0,//1校验手机号码， 2派送
        formData:{
          cardNum:null,
          userType:'',
          userList:null,
        },
        result:null,
      }
    },
    computed:{
      cardType(){
        console.log(typeOption, this.couponDetail)
        for(let i =0;i < typeOption.length;i++){
          if(typeOption[i].name == this.couponDetail.type){
            return typeOption[i].value
          }
        }
      },
      remainderNum(){
        console.log('发放数量', this.couponDetail.issueCount, '领取数量', this.couponDetail.takeCount);
        return this.couponDetail.issueCount - this.couponDetail.takeCount ;
      },    
    },
    watch:{
    },
    render:function(createElement){


    },
 

    methods:{
      handleChange(file, fileList){
        // console.log('handleChange', file);
        this.path = file && file.name ? file.name :'';
        this.result = null;
        this.parseXlsx(file, fileList)
      },
      parseXlsx(file, fileList){
        // console.log('analysisXlsx', file, fileList)
        let reader = new FileReader();
        if (file && file.raw) {
          reader.readAsBinaryString(file.raw);
        } else {
          this.$message(`无数据`);
        }
        reader.onloadend = ()=> {/*读取成功 */
          /*解析*/
          const result = reader.result
          const wb = XLSX.read(result,{type:'binary'})
          /* Get first worksheet */
          const wsname = wb.SheetNames[0];
          const ws = wb.Sheets[wsname];
          const data = XLSX.utils.sheet_to_json(ws, {header:1});

          /* Update state */
          const telList = this.setTelList(data)
          this.formData.userList = telList.join('\r\n');
          this.$message(`导入${telList.length}条手机号码！`);
          
        }
      },
      setTelList(data){
        /*
        将excel里的合格手机号返回一个数组
        return array
        */
        let telList =[];
        for(let x in data){
          if(regTel(data[x])){
            telList = telList.concat(Number(data[x]))
          }
        }
        return telList
      },
      async getCouponDetail(id){
        try{
          let back = await getCouponDetail(id)
          back = back.data
          if(back && back.resultCode == '200'){
            this.couponDetail = back.result;
          }else{
            this.$alert(back.msg);
          }
        }catch(err){
          console.error(err)
        }
      },
      verifyTels(){
        if(this.isAjax)return
        this.$refs.formData.validate((valid) => {
          if (valid) {
            this.postCheckUserValidate()
          }
        })
      },
      sendCoupon(){
        console.log('sendCoupon', this.formData)
        if(this.isAjax)return
        if(this.formData.userType == 3){
          /*
          *@param userType 
          *如果派送给指定用户
          *1、导入手机号码或者手动输入手机号码
          *2、校验导入的手机号码
          *3、向校验成功的账户发券
          */
          if(this.result == null){ //没有查询
            this.$alert('请先校验手机号码');
            return
          }else if(this.result == '没有符合条件的手机号' ){
            this.$alert('没有符合条件的手机号');
            return
          }
        }
        this.$refs.formData.validate((valid) => {
          if (valid) {
            console.log('submit!');
            if(this.formData.userType != 3){
              //派送给非指定用户要二次确认
              let user = this.formData.userType ==1 ?'全部用户':'已绑卡用户';
              this.$alert(`确认给${user}派发卡券？`,{
                callback:action=>{
                  if(action =='confirm'){
                    //确认发送
                    this.postSendCoupon()
                  }
                }
              })
            }else{
              this.postSendCoupon()
            }
            
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      formatUserList(list){//入参的手机号换行符必须为:\r\n
        if(!list) return list
        let re =/\n+/g,
            newList;
        newList = list.replace(re, '\r\n');
        console.log(newList)
        return newList
      },
      async postCheckUserValidate(){ //验证手机号
        try{
          this.isAjax = 1;
          console.warn('postCheckUserValidate')
          let param ={
            cardNum:this.formData.cardNum,
            userList:'',
          };
          param.userList = this.formatUserList(this.formData.userList)
          let back = await postCheckUserValidate(param)
          back = back.data;
          console.log('验证手机号', back)
          this.isAjax = 0;
          if(back && back.resultCode == '200' && back.result){

            this.result = back.result;

            
          }else{
            this.result = back.msg
          }
        }catch(err){
          this.isAjax = 0;
          console.error(err)
        }
      },
      async postSendCoupon(){ //批量送券
        try{
          this.isAjax = 2;
          let param ={
            uuid:this.uuid,
            financialId:sessionStorage.getItem('HKid'),
            type:this.formData.userType,
            cardNum:this.formData.cardNum,
            userList:'',
          };
          param.userList = this.formatUserList(this.formData.userList)
          let back = await postSendCoupon(param)
          back = back.data;
          console.log('postSendCoupon', back)
          this.isAjax = 0;
          if( back && back.resultCode == '200' ){
            let msg = back.result.totalSuccessNum ?  `成功派送${back.result.totalSuccessNum}张卡券` : back.result;
            this.$alert(msg, {
              confirmButtonText: '确定',
              callback: action => {
                this.initData()
              }
            });
          }else{
            this.$alert(back.result, {
              confirmButtonText: '确定',
            });
          }
        }catch(err){
          this.isAjax = 0;
          console.error(err)
        }
      },
      initData(){
        this.isPublishSucced = true;
        this.formData.cardNum = 1;
        this.formData.userList = null;
        this.formData.userType = null;
        this.result = null;
        this.path =''

      },
      goPage(name){
        this.$emit('isPublishSucced', this.isPublishSucced)
        this.$router.push({
            name:name,
        })
      }
    },
    created(){
      this.$emit('setTitleMsg', ['卡券管理','卡券列表','发放'])
      this.getCouponDetail(this.uuid)
      
    },
    destroyed(){
        this.$emit('setTitleMsg', ['卡券管理', '卡券列表'])
    },
  }
</script>